import time
import requests
import os
import base64
import csv


API_Key='BEnNWcDdA6i6X2yxEDFG5D8z'
Secret_Key='SvD8R0kITehaQ1dlnqDbdNaNs0NxQ6ko'
host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={}&client_secret={}'.format(API_Key,Secret_Key)
response = requests.get(host)
access_token = response.json()['access_token']
print(access_token)

os.getcwd()  # 获取当前路径
rootpath = 'E:\\博三\\文本分析\\分析师颜值\\SAC_url_img\\'
os.chdir(rootpath)  # 设置文件夹所在的位置
file_name = os.listdir(".")
result_list = []
reslut_title = ['登记编号','执业机构','姓名','年龄','人脸评分','性别','脸型','眼镜']
result_list.append(reslut_title)

for i in file_name:
    strlist = i.split('-')[0:3]
    img_src = rootpath + i
    print(img_src)
    with open(img_src, 'rb') as f:
        base64_data = base64.b64encode(f.read())

    request_url = "https://aip.baidubce.com/rest/2.0/face/v3/detect"
    params = {
        "image": base64_data,
        "image_type": "BASE64",
        "face_field": "age,beauty,expression,face_shape,gender,glasses,emotion,face_type,spoofing",
        "face_type": "LIVE"
    }
    request_url = request_url + "?access_token=" + access_token
    headers = {
        'content-type': 'application/json'
    }
    response = requests.post(request_url, data=params, headers=headers)
    face_result = response.json()
    face_r = face_result['result']['face_list'][0]

    strlist.append(face_r['age'])
    strlist.append(face_r['beauty'])
    strlist.append(face_r['gender']['type'])
    strlist.append(face_r['face_shape']['type'])
    strlist.append(face_r['glasses']['type'])
    print(strlist)
    result_list.append(strlist)
    time.sleep(1)

result_file = open('result.csv', 'a', newline='')
write1 = csv.writer(result_file, dialect='excel')
m = len(result_list)
for k in range(m):
    write1.writerow(result_list[k])
result_file.close()










